const { songs } = require('../data/songs.js');

class PlayerManager {
  constructor() {
    this.audioManager = null;
    this.currentSong = null;
    this.isPlaying = false;
    this.playMode = 'loop'; // 'loop', 'single', 'random'
    this.playStatusWatchers = []; // 播放状态监听器列表
    this._isChangingSong = false; // 状态锁
    this._updateTimeout = null; // 防抖定时器
    
    this.init();
  }

  init() {
    try {
      this.audioManager = wx.getBackgroundAudioManager();
      this.initAudioManager();

      // 初始化默认歌曲
      const defaultSong = songs.find(s => s.id === '1');
      if (defaultSong) {
        this.currentSong = defaultSong;
        this.isPlaying = false;

        // 设置音频信息但不播放
        this.audioManager.title = defaultSong.title;
        this.audioManager.singer = defaultSong.artist;
        this.audioManager.coverImgUrl = defaultSong.cover;
        this.audioManager.src = defaultSong.src;
        this.audioManager.pause(); // 确保暂停状态
      }
    } catch (error) {
      console.error('初始化音频管理器失败:', error);
      wx.showToast({
        title: '初始化音频播放器失败',
        icon: 'none'
      });
    }
  }

  initAudioManager() {
    if (!this.audioManager) return;

    this.audioManager.onPlay(() => {
      if (this._isChangingSong) return;
      this.isPlaying = true;
      this.updatePlayStatus();
      wx.hideLoading();
    });

    this.audioManager.onPause(() => {
      if (this._isChangingSong) return;
      this.isPlaying = false;
      this.updatePlayStatus();
      wx.hideLoading();
    });

    this.audioManager.onStop(() => {
      if (this._isChangingSong) return;
      this.isPlaying = false;
      this.updatePlayStatus();
      wx.hideLoading();
    });

    this.audioManager.onEnded(() => {
      this.isPlaying = false;
      this.updatePlayStatus();
      wx.hideLoading();
      setTimeout(() => this.playNext(), 100);
    });

    this.audioManager.onError((err) => {
      console.error('播放管理器: 播放错误', err);
      this.isPlaying = false;
      this._isChangingSong = false;
      this.updatePlayStatus();
      wx.hideLoading();
      
      let errMsg = '播放出错了';
      switch (err.errCode) {
        case 10001: errMsg = '系统错误'; break;
        case 10002: errMsg = '网络错误'; break;
        case 10003: errMsg = '文件错误'; break;
        case 10004: errMsg = '格式错误'; break;
        default: errMsg = '未知错误';
      }
      
      wx.showToast({
        title: errMsg,
        icon: 'none'
      });
    });

    this.audioManager.onWaiting(() => {
      if (this._isChangingSong) return;
      wx.showLoading({
        title: '加载中...',
        mask: false
      });
      setTimeout(() => {
        wx.hideLoading();
      }, 3000);
    });

    this.audioManager.onCanplay(() => {
      wx.hideLoading();
    });
  }

  // 播放指定歌曲
  playSong(song) {
    if (!song || this._isChangingSong) return;
    
    try {
      this._isChangingSong = true;
      wx.hideLoading();
      if (!this.audioManager) return;
      
      // 如果是同一首歌，直接播放
      if (this.currentSong?.id === song.id && this.audioManager.src) {
        this.audioManager.play();
        this._isChangingSong = false;
        return;
      }

      this.currentSong = song;
      this.audioManager.title = song.title || '未知歌曲';
      this.audioManager.singer = song.artist || '未知歌手';
      this.audioManager.coverImgUrl = song.cover || '';
      this.audioManager.src = song.src;
      
      setTimeout(() => {
        this._isChangingSong = false;
        wx.hideLoading();
      }, 100);
    } catch (error) {
      this._isChangingSong = false;
      wx.hideLoading();
      console.error('播放管理器: 播放歌曲失败:', error);
      wx.showToast({
        title: '播放失败',
        icon: 'none'
      });
    }
  }

  // 播放/暂停切换
  togglePlay() {
    if (this._isChangingSong) return;
    
    try {
      if (!this.audioManager) return;
      
      if (!this.currentSong) {
        const defaultSong = songs.find(s => s.id === '1');
        this.playSong(defaultSong);
        return;
      }

      if (this.isPlaying) {
        this.audioManager.pause();
      } else {
        if (!this.audioManager.src) {
          this.playSong(this.currentSong);
        } else {
          this.audioManager.play();
        }
      }
    } catch (error) {
      console.error('播放管理器: 切换播放状态失败:', error);
    }
  }

  // 播放上一首
  playPrev() {
    if (this._isChangingSong) return;
    
    try {
      if (!this.currentSong) {
        const defaultSong = songs.find(s => s.id === '1');
        this.playSong(defaultSong);
        return;
      }

      const currentIndex = songs.findIndex(song => song.id === this.currentSong.id);
      let prevIndex;
      
      switch (this.playMode) {
        case 'random':
          prevIndex = Math.floor(Math.random() * songs.length);
          break;
        case 'single':
          prevIndex = currentIndex;
          break;
        default: // 'loop'
          prevIndex = (currentIndex - 1 + songs.length) % songs.length;
      }
      
      this.playSong(songs[prevIndex]);
    } catch (error) {
      console.error('播放管理器: 播放上一首失败:', error);
    }
  }

  // 播放下一首
  playNext() {
    if (this._isChangingSong) return;
    
    try {
      if (!this.currentSong) {
        const defaultSong = songs.find(s => s.id === '1');
        this.playSong(defaultSong);
        return;
      }

      const currentIndex = songs.findIndex(song => song.id === this.currentSong.id);
      let nextIndex;
      
      switch (this.playMode) {
        case 'random':
          nextIndex = Math.floor(Math.random() * songs.length);
          break;
        case 'single':
          nextIndex = currentIndex;
          break;
        default: // 'loop'
          nextIndex = (currentIndex + 1) % songs.length;
      }

      this.playSong(songs[nextIndex]);
    } catch (error) {
      console.error('播放管理器: 播放下一首失败:', error);
    }
  }

  // 切换播放模式
  togglePlayMode() {
    try {
      const modes = ['loop', 'single', 'random'];
      const currentIndex = modes.indexOf(this.playMode);
      this.playMode = modes[(currentIndex + 1) % modes.length];
      
      const modeText = {
        loop: '列表循环',
        single: '单曲循环',
        random: '随机播放'
      };
      
      wx.showToast({
        title: modeText[this.playMode],
        icon: 'none'
      });
    } catch (error) {
      console.error('播放管理器: 切换播放模式失败:', error);
    }
  }

  // 监听播放状态变化
  watchPlayStatus(callback) {
    if (typeof callback === 'function' && !this.playStatusWatchers.includes(callback)) {
      this.playStatusWatchers.push(callback);
      // 立即执行一次回调，同步当前状态
      callback({
        currentSong: this.currentSong,
        isPlaying: this.isPlaying
      });
    }
  }

  // 取消监听播放状态变化
  unwatchPlayStatus(callback) {
    const index = this.playStatusWatchers.indexOf(callback);
    if (index > -1) {
      this.playStatusWatchers.splice(index, 1);
    }
  }

  // 更新播放状态（添加防抖）
  updatePlayStatus() {
    if (this._updateTimeout) {
      clearTimeout(this._updateTimeout);
    }
    
    this._updateTimeout = setTimeout(() => {
      const status = {
        currentSong: this.currentSong,
        isPlaying: this.isPlaying
      };
      
      // 通知所有监听器
      this.playStatusWatchers.forEach(callback => {
        try {
          callback(status);
        } catch (error) {
          console.error('播放状态更新回调执行失败:', error);
        }
      });
    }, 50); // 50ms 防抖
  }
}

// 创建单例实例
const playerManager = new PlayerManager();

module.exports = playerManager; 